import { Tool } from '../../../Tool';
import mapboxgl from 'mapbox-gl';

/**
 * @description: 框选工具
 * @author: zhao_sk
 * @date: 2022-04-08 11:04:34
 */
export class SelectionTool extends Tool {
	constructor(viewer, ...arg) {
		super(arguments);
		this.viewer = viewer;
		this.canvas = null;
		this.startFlag = null;
		this.current = null;
		this.box = null;
		[...arguments].forEach((item) => {
			if (typeof item === 'function') {
				this.callback = item;
			}
		});
	}

	start() {
		let _this = this;
		this.addLayer();
		this.viewer.boxZoom.disable();
		this.canvas = this.viewer.getCanvasContainer();
		this.canvas.addEventListener('mousedown', this.mouseDown, true);
	}

	mousePos = (e) => {
		let rect = this.canvas.getBoundingClientRect();
		return new mapboxgl.Point(
			e.clientX - rect.left - this.canvas.clientLeft,
			e.clientY - rect.top - this.canvas.clientTop
		);
	};

	mouseDown = (e) => {
		// Continue the rest of the function if the shiftkey is pressed.
		if (!(e.shiftKey && e.button === 0)) return;

		// Disable default drag zooming when the shift key is held down.
		this.viewer.dragPan.disable();

		// Call functions for the following events
		document.addEventListener('mousemove', this.onMouseMove);
		document.addEventListener('mouseup', this.onMouseUp);
		document.addEventListener('keydown', this.onKeyDown);

		// Capture the first xy coordinates
		this.startFlag = this.mousePos(e);
	};

	onMouseMove = (e) => {
		// Capture the ongoing xy coordinates
		this.current = this.mousePos(e);

		// Append the box element if it doesnt exist
		if (!this.box) {
			this.box = document.createElement('div');
			this.box.classList.add('boxdraw');
			this.canvas.appendChild(this.box);
		}

		let minX = Math.min(this.startFlag.x, this.current.x),
			maxX = Math.max(this.startFlag.x, this.current.x),
			minY = Math.min(this.startFlag.y, this.current.y),
			maxY = Math.max(this.startFlag.y, this.current.y);

		// Adjust width and xy position of the box element ongoing
		let pos = 'translate(' + minX + 'px,' + minY + 'px)';
		this.box.style.transform = pos;
		this.box.style.WebkitTransform = pos;
		this.box.style.width = maxX - minX + 'px';
		this.box.style.height = maxY - minY + 'px';
		this.box.style.border = '1px solid';
	};

	onMouseUp = (e) => {
		// Capture xy coordinates
		this.finish([this.startFlag, this.mousePos(e)]);
	};

	onKeyDown = (e) => {
		// If the ESC key is pressed
		if (e.keyCode === 27) this.finish();
	};

	finish = (bbox) => {
		// Remove these events now that finish has been called.
		document.removeEventListener('mousemove', this.onMouseMove);
		document.removeEventListener('keydown', this.onKeyDown);
		document.removeEventListener('mouseup', this.onMouseUp);

		if (this.box) {
			this.box.parentNode.removeChild(this.box);
			this.box = null;
		}

		// If bbox exists. use this value as the argument for `queryRenderedFeatures`
		if (bbox) {
			let features = this.viewer.queryRenderedFeatures(bbox, { layers: ['testPoint'] });
			this.callback && this.callback(features);
		}

		this.viewer.dragPan.enable();
	};

	addLayer() {
		let geom = [
			[106.18526423073746, 29.24727325430078],
			[106.18557598860605, 29.244444254375423],
			[106.18551363623044, 29.242231777237293],
			[106.18245840151542, 29.24208669510935],
			[106.18216742717783, 29.24431731025072],
			[106.18098274460442, 29.246874297476893],
			[106.17823926811036, 29.246511608115497],
			[106.17894592100305, 29.24455306350133],
			[106.17846789094443, 29.24254007608043],
			[106.1715884168915, 29.24230431822471],
			[106.1725444763099, 29.245078972655335],
			[106.16903199532857, 29.244879490188893],
			[106.17059078832222, 29.246511608115497]
		];
		let arr = [];
		geom.forEach((item, index) => {
			arr.push({
				type: 'Feature',
				properties: {
					name: index
				},
				geometry: {
					type: 'Point',
					coordinates: item
				}
			});
		});
		this.viewer.addSource('testPoint', {
			type: 'geojson',
			data: {
				type: 'FeatureCollection',
				features: arr
			}
		});
		this.viewer.addLayer({
			id: 'testPoint',
			source: 'testPoint',
			type: 'circle',
			paint: {
				// 绘制类属性
				'circle-opacity': 0.8, // 圆点的不透明度（可选，取值范围为 0 ~ 1，默认值为 1）
				'circle-radius': 6, // 圆点的半径（可选，值 >= 0，默认值为 5，单位：像素）
				'circle-color': '#06CEAE', // 圆点的颜色（可选，默认值为 #000000）
				'circle-blur': 0, // 圆点的虚化（可选，默认值为 0。当值为 1 时，表示把圆虚化到只有圆心是不透明的）
				'circle-stroke-width': 0, // 圆点的描边宽度（可选，值 >= 0，默认值为 0，单位：像素）
				'circle-stroke-color': '#06CEAE', // 圆点的描边颜色（可选，默认值为 #000000）
				'circle-stroke-opacity': 1 // 圆点的描边不透明度（可选，取值范围为 0 ~ 1，默认值为 1）
			}
		});
	}

	cancel() {
		document.removeEventListener('mousemove', this.onMouseMove);
		document.removeEventListener('keydown', this.onKeyDown);
		document.removeEventListener('mouseup', this.onMouseUp);
		this.canvas.removeEventListener('mousedown', this.mouseDown, true);
	}
}
SelectionTool.toolId = 'SelectionTool';
